package com.xinxing.learning.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.xinxing.learning.datasource.context.DynamicContextHolder;
import com.xinxing.learning.datasource.context.SpringContextUtils;
import com.xinxing.learning.datasource.util.DynamicDBUtil;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {

    public static Map<Object, Object> targetDataSources = new HashMap<>(10);

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicContextHolder.peek();
    }

    public static void setDataSource(String dbKey) {
        if (!DynamicDataSource.targetDataSources.containsKey(dbKey)) {
            DruidDataSource dataSource = DynamicDBUtil.getDbSourceByDbKey(dbKey);
            DynamicDataSource.targetDataSources.put(dbKey, dataSource);
        }

        DynamicContextHolder.push(dbKey);
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtils.getBean("dynamicDataSource");
        dynamicDataSource.afterPropertiesSet();
    }
}
